<template>
  <el-dialog
    v-model:visible="dialogVisible"
    title="选择客户"
    width="800px"
    :before-close="handleClose"
  >
    <!-- 搜索条件 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="证件类型">
        <el-select v-model="searchForm.idType" placeholder="请选择证件类型" clearable>
          <el-option label="身份证" value="1"></el-option>
          <el-option label="护照" value="2"></el-option>
          <el-option label="营业执照" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="证件号码">
        <el-input v-model="searchForm.idNumber" placeholder="请输入证件号码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchCustomers">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 客户列表 -->
    <el-table :data="customers" style="width: 100%" @row-click="handleRowClick">
      <el-table-column prop="customerName" label="客户名称" width="180"></el-table-column>
      <el-table-column prop="idType" label="证件类型" width="120">
        <template #default="{ row }">
          {{ row.idType === '1' ? '身份证' : row.idType === '2' ? '护照' : '营业执照' }}
        </template>
      </el-table-column>
      <el-table-column prop="idNumber" label="证件号码" width="220"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" width="150"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 10px;">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useCustomerStore } from '@/store/customer'
import type { Customer } from '@/types/index'

// 定义类型接口
interface SearchForm {
  customerName: string
  idType: string
  idNumber: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 定义props
const props = defineProps<{
  visible: boolean
}>()

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'customer-selected': [customer: Customer]
}>()

// 使用store
const customerStore = useCustomerStore()

// 状态
const dialogVisible = ref(props.visible)
const searchForm = reactive<SearchForm>({
  customerName: '',
  idType: '',
  idNumber: ''
})
const customers = ref<Customer[]>([])
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 监听props.visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    searchCustomers()
  }
})

// 监听dialogVisible变化
watch(() => dialogVisible.value, (newVal) => {
  if (!newVal) {
    emit('update:visible', false)
  }
})

// 搜索客户
const searchCustomers = async () => {
  try {
    // 使用customer store中的方法搜索客户
    const params = {
      customerName: searchForm.customerName,
      idType: searchForm.idType,
      idNumber: searchForm.idNumber,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    await customerStore.searchCustomers(params)
    customers.value = customerStore.customers
    pagination.total = customerStore.total
  } catch (error) {
    ElMessage.error('查询客户失败：' + (error as Error).message)
    console.error('查询客户失败：', error)
    
    // 如果API调用失败，使用模拟数据
    loadMockData()
  }
}

// 加载模拟数据
const loadMockData = () => {
  setTimeout(() => {
    // 模拟客户数据
    customers.value = [
      {
        id: '1',
        customerName: '张三',
        idType: '1',
        idNumber: '110101199001011234',
        contactPhone: '13800138001',
        address: '北京市朝阳区建国路88号'
      },
      {
        id: '2',
        customerName: '李四',
        idType: '1',
        idNumber: '110101199202022345',
        contactPhone: '13800138002',
        address: '上海市浦东新区陆家嘴金融中心'
      },
      {
        id: '3',
        customerName: '王五',
        idType: '2',
        idNumber: 'E12345678',
        contactPhone: '13800138003',
        address: '广州市天河区天河路385号'
      },
      {
        id: '4',
        customerName: '赵六',
        idType: '3',
        idNumber: '91110105MA00123456',
        contactPhone: '13800138004',
        address: '深圳市南山区科技园'
      }
    ]
    pagination.total = customers.value.length
  }, 300)
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.customerName = ''
  searchForm.idType = ''
  searchForm.idNumber = ''
  pagination.currentPage = 1
  searchCustomers()
}

// 处理行点击事件
const handleRowClick = (row: Customer) => {
  // 选择客户后，向父组件发送选择的客户数据
  emit('customer-selected', row)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  searchCustomers()
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  searchCustomers()
}

// 组件挂载时，如果visible为true，则加载数据
onMounted(() => {
  if (props.visible) {
    searchCustomers()
  }
})
</script>

<style scoped>
.search-form {
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.el-table-row:hover {
  background-color: #e6f7ff;
}

.el-table__row--current > td {
  background-color: #bae7ff !important;
}
</style>